/**
 * 系统管理  菜单管理
 */
<template>
  <div>
    <!-- 搜索筛选 -->
    <el-form ref="searchFrom" :inline="true" :model="formInline" class="user-search">
      <!-- <el-form-item prop="name" label="搜索：">
        <el-input v-model="formInline.name" size="small" placeholder="输入菜单名称" />
      </el-form-item> -->
      <el-form-item>
        <!-- <el-button size="small" type="primary" icon="el-icon-search" @click="search">
          搜索
        </el-button>
        <el-button size="small" type="primary" icon="el-icon-delete" @click="resetForm('searchFrom')">
          重置
        </el-button> -->
        <el-button size="small" type="primary" icon="el-icon-plus" @click="handleEdit()">
          添加
        </el-button>
      </el-form-item>
    </el-form>
    <!--列表-->
    <el-table
      v-loading="loading"
      element-loading-text="拼命加载中"
      :data="listData"
      style="width: 100%"
      row-key="menuId"
      border
      lazy
      :tree-props="{children: 'children', hasChildren: 'hasChildren'}"
    >
      <el-table-column prop="name" label="菜单名称" width="200" :show-overflow-tooltip="true" />
      <el-table-column prop="icon" label="图标" align="center" width="50">
        <template slot-scope="scope">
          <svg-icon :icon-class="scope.row.icon!=null ? scope.row.icon : 'kong'" />
        </template>
      </el-table-column>
      <el-table-column prop="sort" label="排序" align="center" width="50" />
      <el-table-column prop="permission" label="权限标识" width="200" :show-overflow-tooltip="true" />
      <el-table-column prop="path" label="组件地址" width="200" :show-overflow-tooltip="true" />
      <el-table-column prop="createTime" label="创建时间" align="center" width="160" />
      <el-table-column align="center" label="操作" min-width="200">
        <template slot-scope="scope">
          <el-button size="mini" type="success" @click="httprequest(scope.$index, scope.row)">
            新增
          </el-button>
          <el-button size="mini" @click="handleEdit(scope.$index, scope.row)">
            编辑
          </el-button>
          <el-button size="mini" type="danger" @click="deptDelete(scope.$index, scope.row)">
            删除
          </el-button>
        </template>
      </el-table-column>
    </el-table>
    <!-- 编辑界面 -->
    <el-dialog
      v-if="editFormVisible"
      :title="title"
      :visible.sync="editFormVisible"
      width="600px"
      :close-on-click-modal="false"
    >
      <el-form ref="editForm" label-width="80px" :model="editForm" :rules="rules">
        <el-row>
          <el-col :span="24">
            <el-form-item label="上级菜单">
              <treeselect
                v-model="editForm.parentId"
                :options="menuOptions"
                :normalizer="normalizer"
                :show-count="true"
                placeholder="选择上级菜单"
              />
            </el-form-item>
          </el-col>
          <el-col :span="24">
            <el-form-item label="菜单类型" prop="type">
              <el-radio-group v-model="editForm.type">
                <el-radio label="M">
                  目录
                </el-radio>
                <el-radio label="C">
                  菜单
                </el-radio>
                <el-radio label="A">
                  按钮
                </el-radio>
              </el-radio-group>
            </el-form-item>
          </el-col>
          <el-col :span="24">
            <el-form-item v-if="editForm.type != 'A'" label="菜单图标">
              <el-popover
                placement="bottom-start"
                width="460"
                trigger="click"
                @show="$refs['iconSelect'].reset()"
              >
                <IconSelect ref="iconSelect" @selected="selected" />
                <el-input slot="reference" v-model="editForm.icon" placeholder="点击选择图标" readonly>
                  <svg-icon
                    v-if="editForm.icon"
                    slot="prefix"
                    :icon-class="editForm.icon"
                    class="el-input__icon"
                    style="height: 32px;width: 16px;"
                  />
                  <i v-else slot="prefix" class="el-icon-search el-input__icon" />
                </el-input>
              </el-popover>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="菜单名称" prop="name">
              <el-input v-model="editForm.name" placeholder="请输入菜单名称" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="显示排序" prop="sort">
              <el-input-number v-model="editForm.sort" controls-position="right" :min="0" />
            </el-form-item>
          </el-col>
          <el-col v-if="editForm.type != 'A'" :span="12">
            <el-form-item label="路由地址" prop="url">
              <el-input v-model="editForm.url" placeholder="请输入路由地址" />
            </el-form-item>
          </el-col>
          <el-col v-if="editForm.type == 'C'" :span="12">
            <el-form-item label="组件路径" prop="path">
              <el-input v-model="editForm.path" placeholder="请输入组件路径" />
            </el-form-item>
          </el-col>
          <el-col v-if="editForm.type != 'M'" :span="12">
            <el-form-item label="权限标识" prop="permission">
              <el-input v-model="editForm.permission" placeholder="请输入权限标识" />
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button size="small" @click="closeDialog">
          取消
        </el-button>
        <el-button size="small" type="primary" :loading="loading" class="title" @click="submitForm('editForm')">
          保存
        </el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
// listMenu, getMenu, delMenu, addMenu, updateMenu
import { listMenu, addMenu, updateMenu, delMenu } from '@/api/userMG'
import Treeselect from '@riophae/vue-treeselect'
import '@riophae/vue-treeselect/dist/vue-treeselect.css'
import IconSelect from '@/components/IconSelect'
const validateNumber = (rule, value, callback) => {
  const numberReg = /^\d+$|^\d+[.]?\d+$/
  if (value !== '') {
    if (!numberReg.test(value)) {
      callback(new Error('请输入数字'))
    } else {
      // eslint-disable-next-line no-lonely-if
      if (value === '' || value === undefined || value === null) {
        callback()
      } else if (!Number(value)) {
        callback(new Error('请输入[1,2000]之间的数字'))
      } else if (value < 1 || value > 2000) {
        callback(new Error('请输入[1,2000]之间的数字'))
      } else {
        callback()
      }
    }
  } else {
    callback(new Error('请输入值'))
  }
}
export default {
  name: 'Menu',
  components: { Treeselect, IconSelect },
  data () {
    return {
      clearable: false, // 清空搜索框
      nshow: true, // switch开启
      fshow: false, // switch关闭
      loading: false, // 是显示加载
      listData: [], // 菜单列表数据
      editFormVisible: false, // 控制编辑页面显示与隐藏
      menuOptions: [], // 菜单树选项
      title: '',
      // 添加编辑
      editForm: {
        menuId: '',
        name: '',
        permission: '',
        path: '',
        url: '',
        method: '',
        parentId: '',
        icon: '',
        sort: '',
        type: '',
        createTime: '',
        updateTime: ''
      },
      // 删除菜单
      seletedata: {
        menuId: ''
      },
      // rules表单验证
      rules: {
        parentId: [{ required: true, message: '请选择上级菜单', trigger: 'change', type: 'number' }],
        sort: [{ required: true, validator: validateNumber, trigger: 'blur' }],
        name: [{ required: true, message: '请输入菜单名称', trigger: 'blur' },
          { min: 3, max: 10, message: '长度在 3 到 20 个字符', trigger: 'blur' }],
        path: [{ required: true, message: '请输入路由地址', trigger: 'blur' },
          { min: 1, max: 128, message: '长度在 1 到 128 个字符', trigger: 'blur' }],
        permission: [{ required: true, message: '请输入权限标识', trigger: 'blur' },
          { min: 1, max: 128, message: '长度在 1 到 128 个字符', trigger: 'blur' }]
      },
      formInline: {
        // name: ''
      }
    }
  },
  /**
   * 创建完毕
   */
  created () {
    this.getdata(this.formInline)
  },
  methods: {
    // 选择图标
    selected (name) {
      this.editForm.icon = name
    },
    // 获取菜单列表
    getdata (parameter) {
      this.loading = true
      /***
       * 调用接口，注释上面模拟数据 取消下面注释
       */
      listMenu(parameter)
        .then((res) => {
          this.loading = false
          if (res.code !== 0) {
            this.$message({
              type: 'info',
              message: res.msg
            })
          } else {
            this.listData = res.data
          }
        })
        // eslint-disable-next-line handle-callback-err
        .catch((err) => {
          this.loading = false
          this.$message.error('菜单加载失败，请稍后再试！')
        })
    },
    // 搜索事件
    search () {
      this.getdata(this.formInline)
    },
    // 重置按钮
    resetForm (formName) {
      // 重置要看 <el-form-item>的组件元素上是否指定了字段名。指定了才会重置生效
      this.$refs[formName].resetFields()
      this.getdata(this.formInline)
    },
    // 显示编辑界面
    handleEdit (index, row) {
      this.getTreeselect()
      this.editFormVisible = true
      if (row !== undefined && row !== 'undefined') {
        this.title = '编辑'
        this.editForm.menuId = row.menuId
        this.editForm.name = row.name
        this.editForm.permission = row.permission
        this.editForm.path = row.path
        this.editForm.url = row.url
        this.editForm.method = row.method
        this.editForm.parentId = row.parentId
        this.editForm.icon = row.icon
        this.editForm.sort = row.sort
        this.editForm.type = row.type
        this.editForm.createTime = row.createTime
        this.editForm.updateTime = row.updateTime
      } else {
        this.title = '添加'
        this.editForm.menuId = ''
        this.editForm.name = ''
        this.editForm.permission = ''
        this.editForm.path = ''
        this.editForm.url = ''
        this.editForm.method = ''
        this.editForm.parentId = 0
        this.editForm.icon = ''
        this.editForm.sort = ''
        this.editForm.type = 'M'
        this.editForm.createTime = ''
        this.editForm.updateTime = ''
      }
    },
    // 新增
    httprequest (index, row) {
      if (row.type !== 'A') {
        this.getTreeselect()
        this.editFormVisible = true
        this.title = '添加'
        this.editForm.menuId = ''
        this.editForm.name = ''
        this.editForm.permission = ''
        this.editForm.path = ''
        this.editForm.url = ''
        this.editForm.method = ''
        this.editForm.parentId = row.menuId
        this.editForm.icon = ''
        this.editForm.sort = ''
        if (row.type === 'M') {
          this.editForm.type = 'C'
        } else if (row.type === 'C') {
          this.editForm.type = 'A'
        }
        this.editForm.createTime = ''
        this.editForm.updateTime = ''
      } else {
        this.$message.error('按钮下不可以添加')
      }
    },
    // 编辑、增加页面保存方法
    submitForm (editData) {
      this.$refs[editData].validate((valid) => {
        if (valid) {
          if (this.title === '添加') {
            addMenu(this.editForm)
              .then((res) => {
                this.editFormVisible = false
                this.loading = false
                if (res.code === 0) {
                  this.getdata(this.formInline)
                  this.$message({
                    type: 'success',
                    message: '菜单保存成功！'
                  })
                } else {
                  this.$message({
                    type: 'info',
                    message: res.msg
                  })
                }
              })
              // eslint-disable-next-line handle-callback-err
              .catch((err) => {
                this.editFormVisible = false
                this.loading = false
                this.$message.error('菜单保存失败，请稍后再试！')
              })
          }
          if (this.title === '编辑') {
            updateMenu(this.editForm)
              .then((res) => {
                this.editFormVisible = false
                this.loading = false
                if (res.code === 0) {
                  this.getdata(this.formInline)
                  this.$message({
                    type: 'success',
                    message: '菜单保存成功！'
                  })
                } else {
                  this.$message({
                    type: 'info',
                    message: res.msg
                  })
                }
              })
              // eslint-disable-next-line handle-callback-err
              .catch((err) => {
                this.editFormVisible = false
                this.loading = false
                this.$message.error('菜单保存失败，请稍后再试！')
              })
          }
        } else {
          return false
        }
      })
    },
    // 删除菜单
    deptDelete (index, row) {
      this.$confirm('确定要删除吗?', '信息', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      })
        .then(() => {
          // eslint-disable-next-line no-undef
          delMenu(row.menuId)
            .then((res) => {
              if (res.code === 0) {
                this.getdata(this.formInline)
                this.$message({
                  type: 'success',
                  message: '菜单已删除!'
                })
                this.getdata(this.formInline)
              } else {
                this.$message({
                  type: 'info',
                  message: res.msg
                })
              }
            })
            // eslint-disable-next-line handle-callback-err
            .catch((err) => {
              this.loading = false
              this.$message.error('菜单删除失败，请稍后再试！')
            })
        })
        .catch(() => {
          this.$message({
            type: 'info',
            message: '已取消删除'
          })
        })
    },
    // 分页插件事件
    callFather (parm) {
      this.getdata(this.formInline)
    },
    // 关闭编辑、增加弹出框、并清空数据
    closeDialog () {
      this.editFormVisible = false
      // this.$refs[formName].resetFields()
      // this.$nextTick(() => {
      //   this.$refs.editForm.resetFields()
      // })
    },
    /** 转换菜单数据结构 */
    normalizer (node) {
      if (node.children && !node.children.length) {
        delete node.children
      }
      return {
        id: node.menuId,
        label: node.name,
        children: node.children
      }
    },
    /** 查询菜单下拉树结构 */
    getTreeselect () {
      listMenu()
        .then((res) => {
          this.loading = false
          if (res.code !== 0) {
            this.$message({
              type: 'info',
              message: res.msg
            })
          } else {
            this.menuOptions = []
            const menu = { menuId: 0, name: '主类目', children: [] }
            menu.children = res.data
            this.menuOptions.push(menu)
          }
        })
        // eslint-disable-next-line handle-callback-err
        .catch((err) => {
          this.loading = false
          this.$message.error('上级菜单加载失败，请稍后再试！')
        })
    }
  }
}
</script>
<style lang="scss">

</style>
